<template>
  <el-form
    ref="ruleFormRef"
    :model="newFormInline"
    :rules="formRules"
    label-width="120px"
    class="w-full"
  >
    <el-form-item label="所属频道" prop="channelId">
      <!-- 将选择器改为只读，并默认选中传入的频道 -->
      <el-select
        v-model="newFormInline.channelId"
        placeholder="请选择频道"
        :disabled="true"
      >
        <el-option
          v-for="option in channelOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="选择用户" prop="userId">
      <el-select
        v-model="newFormInline.userId"
        multiple
        collapse-tags
        placeholder="请选择用户"
      >
        <el-option
          v-for="option in userOptions"
          :key="option.value"
          :label="option.label"
          :value="option.value.toString()"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="类型" prop="type">
      <el-radio-group v-model="newFormInline.type">
        <el-radio :value="0">白名单</el-radio>
        <el-radio :value="1">黑名单</el-radio>
      </el-radio-group>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { ref, withDefaults, onMounted } from "vue";
import { FormProps } from "../componentsUtils/type/channelMembersTypes";
import { formRules } from "../componentsUtils/rule/channelMembersRules";
const props = withDefaults(
  defineProps<{
    formInline?: any;
    title?: string;
    channelOptions?: { label: string; value: number }[];
    userOptions?: { label: string; value: number }[];
  }>(),
  {
    formInline: () => ({
      id: 0,
      dealerId: 0,
      tenantId: 0,
      channelId: 0,
      userId: "", // 空字符串，多选时为空
      type: 0 // 默认为白名单
    }),
    title: "",
    channelOptions: () => [
      {
        label: "无频道",
        value: 0
      }
    ],
    userOptions: () => [
      {
        label: "无用户",
        value: 0
      }
    ]
  }
);

const newFormInline = ref(props.formInline);
const ruleFormRef = ref();

function getRef() {
  return ruleFormRef.value;
}
// 添加获取表单数据的方法，参考userForm.vue
function getFormData() {
  // 返回处理后的表单数据，确保userId是逗号分隔的字符串
  return processFormData();
}
onMounted(() => {
  // 如果父组件传入了channelId，则设置为选中状态，不再重置为0
  if (!newFormInline.value.channelId) {
    newFormInline.value.channelId = 0;
  }
  // 初始化userId为空数组，多选模式
  newFormInline.value.userId = [];
  // 设置默认类型为白名单(0)
  if (!newFormInline.value.type) {
    newFormInline.value.type = 0;
  }
});

// 在表单提交前处理userId，将数组转为逗号分隔的字符串
function processFormData() {
  const formData = { ...newFormInline.value };
  if (Array.isArray(formData.userId)) {
    formData.userId = formData.userId.join(",");
  }
  return formData;
}

defineExpose({ getRef, getFormData });
</script>
